//
//  InformationFeedback.m
//  WestAir
//
//  Created by s on 16/9/25.
//  Copyright © 2016年 Henry. All rights reserved.
//

#import "InformationFeedback.h"
#import "PhotoSelectView.h"
#import "CMCCIOTIGSharePopWindow.h"

@interface InformationFeedback ()<PhotoSelectDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>{

    UIImage  *imagePhoto;
}

@property (weak, nonatomic) IBOutlet UIButton *btnSum;

@property (weak, nonatomic) IBOutlet UITextView *textFeedBack;
@property (weak, nonatomic) IBOutlet UITextField *xianJIn;
@property (weak, nonatomic) IBOutlet UITextField *shuaKa;
@property (weak, nonatomic) IBOutlet UITextField *diYongJuan;
@property (weak, nonatomic) IBOutlet UIView *viewFeedBack;
@property (weak, nonatomic) IBOutlet UIView *viewJinE;
@property (weak, nonatomic) IBOutlet UIImageView *imagePhoto;

@end

@implementation InformationFeedback

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    _btnSum.backgroundColor=NORMAL_BULUE_COLOR;
    VIEW_CORNER(_btnSum, buttonCorner21);
    
    self.xianJIn.keyboardType=UIKeyboardTypeDecimalPad;
    self.diYongJuan.keyboardType=UIKeyboardTypeDecimalPad;
    self.shuaKa.keyboardType=UIKeyboardTypeDecimalPad;
    
    VIEW_CORNER(_viewJinE, 4.0);
    VIEW_CORNER(_viewFeedBack, 4.0);
    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    
    NSDictionary  *dicTem=@{@"FID":[NSString stringWithFormat:@"%ld",hangBan.FID]};
    
    NSDictionary  *dicJson= [CMCCIOTIGUnity   getRequestJson:dicTem];
    [[NetworkFactory  alloc]  startPostRequestWithURL:FEEDBACKContent andPostValues:dicJson andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
            NSArray  *arrMainData;
            if ([responseJson[@"data"]  isKindOfClass:[NSArray  class]]) {
                arrMainData=responseJson[@"data"];
            }
            else{
                arrMainData=[@[]  mutableCopy];
            }
            if (arrMainData.count) {
                
                NSString  * strContent=[(NSString  *) arrMainData[0][@"FSuggest"]  nullClass]  ;
                NSDictionary  *dicContent=arrMainData[0];
                strContent=  [strContent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                if (strContent.length) {
                    _textFeedBack.text=strContent;
                    self.lablePlaceHolder.text = @"";

                }
               
              _xianJIn.text=[NSString stringWithFormat:@"%.1f",[STRING_FORMAT(dicContent[@"CashSettlementAmount"]) ?STRING_FORMAT(dicContent[@"CashSettlementAmount"]):@""  floatValue]];
              _shuaKa.text=[NSString stringWithFormat:@"%.1f",[STRING_FORMAT(dicContent[@"SwingCardAmount"])?STRING_FORMAT(dicContent[@"SwingCardAmount"]):@""  floatValue]] ;
             _diYongJuan.text=[NSString stringWithFormat:@"%.1f",[STRING_FORMAT(dicContent[@"VoucherAmount"])?STRING_FORMAT(dicContent[@"VoucherAmount"]):@""  floatValue]] ;
                
                if ([_xianJIn.text isEqualToString:@"0.0"] ) {
                    _xianJIn.text=@"";
                }
                if ([_shuaKa.text isEqualToString:@"0.0"] ) {
                    _shuaKa.text=@"";
                }
                
                if ([_diYongJuan.text isEqualToString:@"0.0"] ) {
                    _diYongJuan.text=@"";
                }
                
                
                
               }
           
            
        }

        
        
    } andFailBlock:^(NSError *error) {
        
        
    } ];

   
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAppearanceChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardAppearanceChanged:(NSNotification *)note
{
    NSDictionary *userInfo = [note userInfo];
    
    NSValue* beginValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    NSValue* endValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyBoardRectBegin = [beginValue CGRectValue];
    CGRect keyBoardRectEnd = [endValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [self moveInputBarWithKeyboardRectFrom:keyBoardRectBegin to:keyBoardRectEnd withDuration:animationDuration];
    
}
-(void)moveInputBarWithKeyboardRectFrom:(CGRect)rectBegin to:(CGRect)rectEnd withDuration:(NSTimeInterval)timeInternal{
    
    [UIView beginAnimations:@"changeAlertView" context:nil];
    
    float keyBoardOriginY   = rectEnd.origin.y;
    if (390>keyBoardOriginY&&![_textFeedBack isFirstResponder]) {
        
        [self.view setOrigin:CGPointMake(0,keyBoardOriginY- 390)];
        [UIView setAnimationDuration:timeInternal+0.5];
    }
    else{
        
        [self.view setOrigin:CGPointMake(0,0)];
        [UIView setAnimationDuration:0];
    }
    [UIView commitAnimations];
    
}


- (IBAction)popBack:(id)sender {
    
    
    [self.navigationController  popViewControllerAnimated:YES];
}


-(void)textViewDidChange:(UITextView *)textView
{
   
    if (textView.text.length == 0) {
        self.lablePlaceHolder.text = @"信息反馈";
    }else{
        self.lablePlaceHolder.text = @"";
    }
}


- (IBAction)btnSumb:(id)sender {
    
    NSString  *feedBack=  [self.textFeedBack.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if ([CMCCIOTIGUnity isIllegal:feedBack]) {
        [CMCCIOTTipsCenter showErrorWithStatus:ILLEGE_MESSAGE];
        return;
    }
    
    if (feedBack.length==0) {
        [CMCCIOTTipsCenter  showErrorWithStatus:@"请输入反馈内容"];
        return;
    }
    
    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    NSNumber  *FID=[NSNumber  numberWithInteger:hangBan.FID];
    NSString  *FFLIGHTNUMBER=  hangBan.FFLIGHTNUMBER;
    NSString  *FFLIGHTDATE=hangBan.FFLIGHTDATE;
    NSString  *FSuggest=feedBack?feedBack:@"";
    NSString  *xianJin=self.xianJIn.text.length?self.xianJIn.text:@"0";
    NSString  *shuaKa=self.shuaKa.text.length?self.shuaKa.text:@"0";
    NSString  *diYongJuan=self.diYongJuan.text.length?self.diYongJuan.text:@"0";
    
    // 图片压缩
    NSData *imageData = UIImageJPEGRepresentation(imagePhoto, 0.2);
    
    NSDictionary  *dicTem=@{@"FID":FID,@"FNUMBER":FFLIGHTNUMBER,@"FFLIGHTDATE":FFLIGHTDATE,@"FFLIGHTDATE":FFLIGHTDATE,@"FSuggest":FSuggest,@"CashSettlementAmount":xianJin,@"SwingCardAmount":shuaKa,@"VoucherAmount":diYongJuan,@"FPicture":@""};
    NSDictionary  *dicJson= [CMCCIOTIGUnity   getRequestJson:dicTem];
    
    
    NSMutableDictionary  *dicMutableJson=[[NSMutableDictionary  alloc]  initWithDictionary:dicJson];
    
    NSString *path_document = NSHomeDirectory();
    NSString *imagePath = [path_document stringByAppendingString:@"/Documents/pic.png"];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    if (imageData) {
       
        [imageData writeToFile:imagePath atomically:YES];
        
    }
//    [dicMutableJson setObject:imagePath forKey:@"image"];
    
    [[NetworkFactory  alloc]  startPostRequestWithURL:FEEDBACK andPostValues:dicMutableJson andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
             [CMCCIOTTipsCenter  showSuccessWithStatus:responseJson[@"message"]];
            [self.navigationController  popViewControllerAnimated:YES];
        }
    
        
    } andFailBlock:^(NSError *error) {
        

        
    } ];
    

    
}

#pragma mark UITextField Deleget


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField  resignFirstResponder];
    
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view  endEditing:YES];
}

- (IBAction)btnPhoto:(id)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:@"选择照片"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction *action) {
                                                
                                                [self  camaraSelect];
                                                
                                                
                                            }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"相册"
                                              style:UIAlertActionStyleCancel
                                            handler:^(UIAlertAction *action) {
                                                
                                                [self  photoSelect];
                                                
                                                
                                                
                                            }]];

    
    [self presentViewController:alert animated:YES completion:nil];
    
    
    
}

#pragma mark - photoShopDeleget
//相机
- (void)camaraSelect
{
    
    [[CMCCIOTIGSharePopWindow sharedWindow] dismiss];
    
    //判断是否可以打开相机，模拟器此功能无法使用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];//摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = NO;  //是否可编辑
        [self.navigationController presentViewController:picker animated:YES completion:NULL];
    }else{
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    
    
}

// 选择本地照片
- (void)photoSelect
{
    
    [[CMCCIOTIGSharePopWindow sharedWindow] dismiss];
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];// 相册
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;//设置选择后的图片可被编辑
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma  mark -
#pragma  mark UIImagePickerControllerDelegate协议的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *wmImage =  [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    self.imagePhoto.image=wmImage;
    imagePhoto=wmImage;
    [picker dismissViewControllerAnimated:YES completion:^{
        ;
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
